<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/gmxs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/gmxs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/gmxs/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/gmxs/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/gmxs/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/gmxs/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/gmxs/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="技术分享,数据结构,菜鸟笔记," />





  <link rel="alternate" href="/gmxs/atom.xml" title="葛木小舍先生的博客" type="application/atom+xml" />






<meta name="description" content="记录了数据结构线性表中顺序表的储存结构及其实现。">
<meta name="keywords" content="技术分享,数据结构,菜鸟笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="java数据结构线性表——顺序表的设计思想及实现">
<meta property="og:url" content="http://yoursite.com/2018/04/25/数据结构/顺序表/index.html">
<meta property="og:site_name" content="葛木小舍先生的博客">
<meta property="og:description" content="记录了数据结构线性表中顺序表的储存结构及其实现。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://img-blog.csdn.net/20161030092804983">
<meta property="og:updated_time" content="2018-05-01T13:41:07.258Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java数据结构线性表——顺序表的设计思想及实现">
<meta name="twitter:description" content="记录了数据结构线性表中顺序表的储存结构及其实现。">
<meta name="twitter:image" content="https://img-blog.csdn.net/20161030092804983">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/gmxs/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/04/25/数据结构/顺序表/"/>





  <title>java数据结构线性表——顺序表的设计思想及实现 | 葛木小舍先生的博客</title>
  









  
  <script type="text/javascript"
  color="0,0,255" opacity='0.7' zIndex="-2" count="99" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>


	<a href="https://your-url" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; left: 0; transform: scale(-1, 1);" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/gmxs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">葛木小舍先生的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/gmxs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/gmxs/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/gmxs/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/gmxs/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/gmxs/2018/04/25/数据结构/顺序表/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="葛木小舍先生">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/gmxs/images/touxiang.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="葛木小舍先生的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">java数据结构线性表——顺序表的设计思想及实现</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-25T08:57:33+08:00">
                2018-04-25
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/gmxs/categories/数据结构/" itemprop="url" rel="index">
                    <span itemprop="name">数据结构</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/gmxs/2018/04/25/数据结构/顺序表/" class="leancloud_visitors" data-flag-title="java数据结构线性表——顺序表的设计思想及实现">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">热度&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
			 <span>℃</span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,356
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  14
                </span>
              
            </div>
          

          
              <div class="post-description">
                  记录了数据结构线性表中顺序表的储存结构及其实现。
              </div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="线性表抽象数据类型概述"><a href="#线性表抽象数据类型概述" class="headerlink" title="线性表抽象数据类型概述"></a>线性表抽象数据类型概述</h1><hr>
<ul>
<li>什么是抽象数据类型<br>这里引用一段相关描述：<blockquote>
<p>我们都知道java在默认情况下，所有的基本数据类型(int,float,boolean等)都支持基本运算，如加减法，这是因为系统已帮我们实现了这些基本数据类型的的基本运算。而对于自定义的数据类型(如类)也需要定义相应的运算，但在实际使用这些自定义的数据类型的运算时需要自己实现相关的运算，也就是说用户自定义的数据类型的运算需要我们自己利用系统提供的基本运算来定义和实现。这些自定义了数据结构(如自定义类)和包含相关运算组合实现的数据类型就称其为抽象数据类型(ADT,Abstract Data Type),因此一个ADT会包含数据声明和运算声明。常用的ADT包含链表、栈、队列、优先队列、二叉树、散列表、图等，所以接下来我们要分析的顺序表和链表也属于ADT范畴.</p>
<a id="more"></a>
</blockquote>
</li>
</ul>
<hr>
<ul>
<li>Java数据结构中对线性表的定义:</li>
</ul>
<blockquote>
<p> 线性表是由n(n&gt;=0)个类型相同的数据元素a0,a1,…,an-1组成的有限的序列，在数学中记作(a0,a1,…,an-1)，其中ai的数据类型可以是基本数据类型(int,float等)、字符或类。n代表线性表的元素个数，也称其为长度(Length)。若n=0，则为空表；若n &gt; 0，则ai(0 &lt; i &lt; n-1)有且仅有一个前驱(Predecessor)元素ai-1和一个后继(Successor)元素ai+1，a0没有前驱元素，ai没有后继元素。</p>
</blockquote>
<p>以上，便是关于线性表抽象数据类型的概述。</p>
<hr>
<h1 id="线性表的顺序存储设计和实现（顺序表）"><a href="#线性表的顺序存储设计和实现（顺序表）" class="headerlink" title="线性表的顺序存储设计和实现（顺序表）"></a>线性表的顺序存储设计和实现（顺序表）</h1><ul>
<li><h2 id="顺序储存结构的设计原理"><a href="#顺序储存结构的设计原理" class="headerlink" title="顺序储存结构的设计原理"></a>顺序储存结构的设计原理</h2><blockquote>
<p>顺序存储结构底层是利用数组来实现的，而数组可以存储具有相同数据类型的元素集合，如int，float或者自定义类型等，当我们创建一个数组时，计算机操作系统会为该数组分配一块连续的内存块，这也就意味着数组中的每个存储单元的地址都是连续的，因此只要知道了数组的起始内存地址就可以通过简单的乘法和加法计算出数组中第n-1个存储单元的内存地址.</p>
</blockquote>
</li>
</ul>
<p><img src="https://img-blog.csdn.net/20161030092804983" alt="顺序表存储结构图"></p>
<blockquote>
<p> 通过上图可以发现为了访问一个数组元素，该元素的内存地址需要计算其距离数组基地址的偏移量，即用一个乘法计算偏移量然后加上基地址，就可以获得数组中某个元素的内存地址。其中c代表的是元素数据类型的存储空间大小，而序号则为数组的下标索引。整个过程需要一次乘法和一次加法运算，因为这两个操作的执行时间是常数时间，所以我们可以认为数组访问操作能再常数时间内完成，即时间复杂度为O(1)，这种存取任何一个元素的时间复杂度为O(1)的数据结构称之为随机存取结构。</p>
</blockquote>
<p>及<code>a1=a0+c,a2=a1+c,a3=a2+c</code>c代表每个数组元素所占存储空间的大小。因为顺序表是一段连续不断的空间里储存的，所以我们只需要用前一个数组元素的存储位置加上其所占的存储空间大小，就可以得出当前数组元素的存储位置，只需要进行简单的加法和乘法运算就可以实现对顺序表中的元素进行基本的插入，删除，查找操作了。</p>
<p>这里引用一下顺序表的定义：</p>
<blockquote>
<p> 线性表的顺序存储结构称之为顺序表(Sequential List),它使用一维数组依次存放从a0到an-1的数据元素(a0,a1,…,an-1)，将ai(0&lt; i &lt;&gt; n-1)存放在数组的第i个元素，使得ai与其前驱ai-1及后继ai+1的存储位置相邻，因此数据元素在内存的物理存储次序反映了线性表数据元素之间的逻辑次序。</p>
</blockquote>
<hr>
<ul>
<li><h2 id="顺序储存结构的实现"><a href="#顺序储存结构的实现" class="headerlink" title="顺序储存结构的实现"></a>顺序储存结构的实现</h2><p>下面我们分析一下顺序表的实现，前面说了线性表的抽象数据类型的性质，所以我们这里首先要创建一个顺序表接口类用来声明顺序表的各种操作方法。<br>关于接口这里引用Java数据结构中的一段描述：</p>
<blockquote>
<p>java语言的接口是一组抽象方法，常量和内嵌型的集合。接口是多继承的，一个接口可以继承多个父接口，接口是一种数据类型，采用抽象的形式来约定，因此接口只有被类实现之后才有意义。<br>一个接口可被多个类实现，<strong>接口提供方法声明与方法实现是相分离的机制。</strong>使实现接口的多个类表现出共同的行为能力，接口声明的抽象方法在实现接口的多个类中表现出多态性。</p>
</blockquote>
<hr>
<ul>
<li><h3 id="声明接口类"><a href="#声明接口类" class="headerlink" title="声明接口类"></a>声明接口类<list></list></h3></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">  </span><br><span class="line">/**</span><br><span class="line"> * 首先声明一个顺序表的接口类&lt;List&gt;,并实现该接口。</span><br><span class="line"> * 泛型参数T表示数据源数的数据类型</span><br><span class="line"> * 定义线性表ADT的基本操作</span><br><span class="line"> * </span><br><span class="line"> * @author MaYaP</span><br><span class="line"> *</span><br><span class="line"> */</span><br><span class="line">public interface List&lt;T&gt; &#123;</span><br><span class="line"></span><br><span class="line">	boolean isEmpty();  //判断集合是否为空</span><br><span class="line">	</span><br><span class="line">	int length();  //返回线性表的元素个数(长度)</span><br><span class="line">	</span><br><span class="line">	T get(int i); // 返回第i个元素</span><br><span class="line">	</span><br><span class="line">    void set(int i, T x);  //设置第i个元素的值为x</span><br><span class="line">	</span><br><span class="line">	int insert(int i, T x); //插入x作为第i个元素</span><br><span class="line">	</span><br><span class="line">	void append(T x); //在线性表最后插入x元素</span><br><span class="line">	</span><br><span class="line">	T remove (int i); //删除第i个元素并返回被删除的对象</span><br><span class="line">	</span><br><span class="line">	void removeAll(); //删除线性表内所有元素</span><br><span class="line">	</span><br><span class="line">	T search(T key);  //查找，返回首次出现的关键字为key元素,按内容查找</span><br><span class="line">	</span><br><span class="line">	boolean contain(T x); //判断集合是否包含元素x,及元素x是否属于集合</span><br><span class="line">	</span><br><span class="line">	void showListInfo();  //显示表长和表内的所有元素</span><br><span class="line"></span><br><span class="line">		</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>  其次，在声明好了接口类后，我们需要对其中声明的方法进行实现，所以接下来我们需要声明一个实现接口方法的类。用来实现接口类中的各种方法。</p>
<hr>
<ul>
<li><h3 id="声明一个实现接口类方法的类SeqList。及实现接口类各种方法的代码。"><a href="#声明一个实现接口类方法的类SeqList。及实现接口类各种方法的代码。" class="headerlink" title="声明一个实现接口类方法的类SeqList。及实现接口类各种方法的代码。"></a>声明一个实现接口类方法的类SeqList。及实现接口类各种方法的代码。</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br></pre></td><td class="code"><pre><span class="line">  /**</span><br><span class="line"> * 声明一个实现接口类方法的类SeqList。及实现接口类各种方法的代码。</span><br><span class="line"> * @author MaYaP</span><br><span class="line"> *</span><br><span class="line"> * @param &lt;T&gt;</span><br><span class="line"> */</span><br><span class="line"></span><br><span class="line">public class SeqList&lt;T&gt; implements List&lt;T&gt; &#123;</span><br><span class="line">	</span><br><span class="line">	protected Object[] element;  //对象数组存储顺序表的数据类型，保护成员</span><br><span class="line">	protected int n; //顺序表的元素个数</span><br><span class="line">	/**</span><br><span class="line">	 * 构建容量为length的空表</span><br><span class="line">	 * @param length</span><br><span class="line">	 */</span><br><span class="line">	public SeqList(int length) &#123;</span><br><span class="line">		this.element = new Object[length]; // 申请数组的存储空间，元素为null,若数组长度小于0，则抛出负数组异常。</span><br><span class="line">		this.n=0; </span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	/**</span><br><span class="line">	 *创建默认容量的空表。</span><br><span class="line">	 */</span><br><span class="line">	public SeqList()&#123;</span><br><span class="line">		this(64);  //调用本类已声明的指定参数列表的构建方法</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	</span><br><span class="line">	/**</span><br><span class="line">	 * 判断顺序表是否为空，若为空则返回ture</span><br><span class="line">	 */</span><br><span class="line">	@Override</span><br><span class="line">	public boolean isEmpty() &#123;</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		return this.n==0; //双等于判断，单等于是赋值。</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	 * 返回顺序表元素个数，长度。</span><br><span class="line">	 */</span><br><span class="line">	@Override</span><br><span class="line">	public int length() &#123;</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		return this.n;</span><br><span class="line">	&#125;</span><br><span class="line">/**</span><br><span class="line">	 * 按序号查找，返回第i个元素，0&lt;i&lt;n.若i越界，则返回null</span><br><span class="line">	 */</span><br><span class="line">	@Override</span><br><span class="line">	public T get(int i) &#123;</span><br><span class="line">		if(i&gt;=0 &amp;&amp; i&lt;this.n)</span><br><span class="line">		&#123;</span><br><span class="line">			int p=i;</span><br><span class="line">			//return (T)this.element[i];	</span><br><span class="line">		    System.out.println(&quot;position=&quot;+p+&quot;,is:&quot;+this.element[i]);//返回第i个元素</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">		    return null;	</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	 * 设置第i个元素为x，0&lt;i&lt;n,若i越界，则抛出序号越界异常，若i=null，则抛出空对象异常。</span><br><span class="line">	 */</span><br><span class="line">	@Override</span><br><span class="line">	public void set(int i, T x) &#123;</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		if(x==null)</span><br><span class="line">			throw new NullPointerException(&quot;x==null&quot;);//抛出空对象异常</span><br><span class="line">		if(i&gt;=0 &amp;&amp; i&lt;n)</span><br><span class="line">			this.element[i]=x;</span><br><span class="line">		else throw new java.lang.IndexOutOfBoundsException(i+&quot;&quot;);//抛出序号越界异常</span><br><span class="line">			</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">/**</span><br><span class="line"> * 插入x做为第i个元素，x!=null，返回x序号，若x==null,则抛出空对象异常 </span><br><span class="line"> * 对序号i采取容错措施，若i&lt;0,则在表头插入x，若i&gt;n,则在表尾插入x。</span><br><span class="line"> */</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public int insert(int i, T x) &#123;</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		if(x==null)  </span><br><span class="line">			throw new NullPointerException(&quot;x==null&quot;); // 抛出空对象异常</span><br><span class="line">		if(i&lt;0) i=0;  //插入在表头</span><br><span class="line">		if(i&gt;this.n) i=this.n;  //插入在最后</span><br><span class="line">		Object[] source=this.element; // 数组引用赋值，source也引用element</span><br><span class="line">		if(this.n==element.length)  // 如果数组满了，则扩充顺序表的数据容量</span><br><span class="line">		&#123;</span><br><span class="line">			this.element=new Object[source.length*2];  //重新申请一个容量更大的数组</span><br><span class="line">			for(int j=0;j&lt;i;j++)  //复制当前数组前i-1个元素</span><br><span class="line">				this.element[j]=source[j]; </span><br><span class="line">		&#125;</span><br><span class="line">		for(int j=this.n-1;j&gt;=i;j--)  //从i开始至表尾的元素向后移动</span><br><span class="line">			this.element[j]=source[j];</span><br><span class="line">		this.element[i]=x;  </span><br><span class="line">		this.n++;  </span><br><span class="line">		</span><br><span class="line">		System.out.println(&quot;insert a new node:&quot;+this.element[i].toString()+&quot;,in position=&quot;+i);	//输出插入元素信息</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">	return i++;  //返回x序号</span><br><span class="line">	</span><br><span class="line">	</span><br><span class="line">	</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	</span><br><span class="line">	/**</span><br><span class="line">	 * 在线性表尾插入x</span><br><span class="line">	 */</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public void append(T x) &#123;</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">/**</span><br><span class="line"> * 删除第i个元素，0=&lt;i&lt;0,返回被删除元素，若i越界，则返回 null</span><br><span class="line"> */</span><br><span class="line">	@Override</span><br><span class="line">	public T remove(int i) &#123;</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		if(this.n==0 || i&lt;0 || i&gt;this.n )  &#123;</span><br><span class="line">			// throw new IndexOutOfBoundsException(i + &quot;&quot;); // 抛出序号越界异常</span><br><span class="line">			return null;</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">			T old = (T)this.element[i];  //old 中存储被删除元素</span><br><span class="line">			</span><br><span class="line">			System.out.println(&quot;node:&quot;+this.element[i].toString()+&quot;,is Delete from the SeqList&quot;);//输出删除信息</span><br><span class="line">			</span><br><span class="line">			for (int j=i;j&lt;this.n-1;j++)</span><br><span class="line">			&#123;</span><br><span class="line">				this.element[j]=this.element[j+1];  //元素前移一个位置 </span><br><span class="line">			&#125;</span><br><span class="line">				</span><br><span class="line">			this.element[this.n-1]=null; //设置数组元素对象为空，释放原引用实例</span><br><span class="line">			this.n--;</span><br><span class="line">			return old;  //返回old局部变量引用的对象，传递对象引用</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">/**</span><br><span class="line"> * 删除所有元素</span><br><span class="line"> */</span><br><span class="line">	@Override</span><br><span class="line">	public void removeAll() &#123;</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		this.n=0;  //设置长度为0，未释放数组空间 </span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">/**</span><br><span class="line"> * 判断集合是否包含元素x，即元素x是否属于集合</span><br><span class="line"> */</span><br><span class="line">	@Override</span><br><span class="line">	public boolean contain(T x) &#123;</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		return false;</span><br><span class="line">	&#125;</span><br><span class="line">/**</span><br><span class="line"> * 显示表长和表内所有数据元素</span><br><span class="line"> */</span><br><span class="line">	@Override</span><br><span class="line">	public void showListInfo() &#123;</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		//int i=this.length(); </span><br><span class="line">		/**</span><br><span class="line">		 * 使用for循环遍历顺序表，输出表内全部内容</span><br><span class="line">		 */</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		/*for(int i=0;i&lt;this.length();i++)	</span><br><span class="line">		&#123;			</span><br><span class="line">			int p=i; //重新定义一个整型变量p来记录元素下标，以便输出</span><br><span class="line">			</span><br><span class="line">	   	System.out.println(&quot;insert a new node:&quot;+this.element[i]+&quot;,in position=&quot;+p);	</span><br><span class="line">	   	//输出顺序表内所有插入的元素及其对应的下标序号。</span><br><span class="line">		&#125;*/</span><br><span class="line">       </span><br><span class="line">	</span><br><span class="line">		</span><br><span class="line">			</span><br><span class="line">		</span><br><span class="line">		System.out.println(&quot;seqlist len=&quot;+this.length());//输出顺序表的长度length().</span><br><span class="line">		/**</span><br><span class="line">		 * 通过for循环，以（，，，，）的形式输出所有顺序表内的元素。</span><br><span class="line">		 */</span><br><span class="line">		System.out.print(&quot;The seqlist is:(&quot;);//打印括号</span><br><span class="line">		</span><br><span class="line">		/**</span><br><span class="line">		 * for循环，遍历整个顺序表，并输出其中元素。</span><br><span class="line">		 */</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		for(int i=0;i&lt;this.length();i++)&#123;</span><br><span class="line">			System.out.print(this.element[i]+&quot;,&quot;);</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">		System.out.println(&quot;)&quot;);//输出反括号</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">/*</span><br><span class="line"> * 按内容查找</span><br><span class="line"> */</span><br><span class="line">	@Override</span><br><span class="line">	public T search(T key) &#123;</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		return null;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>  其中，关于顺序表的插入，删除，查找，就不在做详细描述了，代码注释都比较详细。</p>
<hr>
<p>  当然，在声明了实现接口的类并且实现了其中的构造方法后。我们需要创建main主函数类来测试实现一下我们的顺序表的构造是否成功。</p>
<hr>
<ul>
<li><h3 id="声明main主函数类测试实现接口和接口实现类"><a href="#声明main主函数类测试实现接口和接口实现类" class="headerlink" title="声明main主函数类测试实现接口和接口实现类"></a>声明main主函数类测试实现<list>接口和接口实现类<seqlist></seqlist></list></h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">  /*</span><br><span class="line"> * 声明main主函数类测试实现&lt;List&gt;接口和接口实现类&lt;SeqList&gt;</span><br><span class="line"> */</span><br><span class="line">public class Main &#123;</span><br><span class="line">	</span><br><span class="line">	public static void main(String args[])&#123;</span><br><span class="line">		//创建顺序表</span><br><span class="line">		SeqList&lt;Integer&gt; list1 =new SeqList&lt;Integer&gt;();//空表</span><br><span class="line">		</span><br><span class="line">		//建表，插入新的数据元素</span><br><span class="line">		System.out.println(&quot;建表操作：&quot;);</span><br><span class="line">		list1.insert(1, 1);  //相当于执行了四次插入操作</span><br><span class="line">		list1.insert(2, 2);</span><br><span class="line">		list1.insert(3, 3);</span><br><span class="line">		list1.insert(4, 4);</span><br><span class="line">		list1.showListInfo(); //调用方法，显示表的长度和表内所有的内容</span><br><span class="line">		</span><br><span class="line">		//查找操作</span><br><span class="line">		System.out.println(&quot;查找操作：&quot;);</span><br><span class="line">		list1.get(3);</span><br><span class="line">		</span><br><span class="line">		//插入操作</span><br><span class="line">		System.out.println(&quot;插入操作：&quot;);</span><br><span class="line">		list1.insert(4, 100);</span><br><span class="line">		list1.showListInfo();</span><br><span class="line">		</span><br><span class="line">		//删除操作</span><br><span class="line">		System.out.println(&quot;删除操作：&quot;);</span><br><span class="line">		list1.remove(3);</span><br><span class="line">		list1.showListInfo();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>  这是一个主函数类，用来测试顺序表的各种操作的实现。</p>
<hr>
<ul>
<li><h2 id="参考"><a href="#参考" class="headerlink" title="参考:"></a>参考:</h2><p><a href="https://blog.csdn.net/javazejian/article/details/52953190" target="_blank" rel="noopener">java数据结构与算法之顺序表与链表深入分析</a></p>
<hr>
<p>更新时间：<br>2018.4.29</p>
</li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你现在可以打赏本宝宝啦！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weixing.png" alt="葛木小舍先生 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/zhifubao.png" alt="葛木小舍先生 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/gmxs/tags/技术分享/" rel="tag"># 技术分享</a>
          
            <a href="/gmxs/tags/数据结构/" rel="tag"># 数据结构</a>
          
            <a href="/gmxs/tags/菜鸟笔记/" rel="tag"># 菜鸟笔记</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/gmxs/2018/04/21/疑难杂症/所碰到的问题及解决方案/" rel="next" title="所碰到的问题及解决方案">
                <i class="fa fa-chevron-left"></i> 所碰到的问题及解决方案
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/gmxs/2019/03/14/前端/html框架/" rel="prev" title="HTML框架结构">
                HTML框架结构 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNTg1Ni8xMjM5Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/gmxs/images/touxiang.png"
                alt="葛木小舍先生" />
            
              <p class="site-author-name" itemprop="name">葛木小舍先生</p>
              <p class="site-description motion-element" itemprop="description">不管过去过的如何，现在活的如何，将来将会如何。努力做好自己，朝梦想中的自己努力前进。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/gmxs/archives/">
              
                  <span class="site-state-item-count">61</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/gmxs/categories/index.html">
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/gmxs/tags/index.html">
                  <span class="site-state-item-count">25</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/gmxs/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/gemuxiaoshe" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:MaYaPeng2017@outlook.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/5967971229/home?wvr=5&sudaref=graph.qq.com" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                个人收集站
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gemumiaoshe.wordpress.com/" title="葛木小舍先生的小世界" target="_blank">葛木小舍先生的小世界</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.w3cschool.cn/html/" title="W3Cschool" target="_blank">W3Cschool</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.alloyteam.com/nav/" title="web前端导航" target="_blank">web前端导航</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.itcast.cn/" title="传智播客" target="_blank">传智播客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://5sing.kugou.com/index.html" title="5sing" target="_blank">5sing</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.mikecrm.com/login.php?s=2&d=form.php#/list/" title="麦客CRM" target="_blank">麦客CRM</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.51cto.com/" title="51CTO" target="_blank">51CTO</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#线性表抽象数据类型概述"><span class="nav-number">1.</span> <span class="nav-text">线性表抽象数据类型概述</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#线性表的顺序存储设计和实现（顺序表）"><span class="nav-number">2.</span> <span class="nav-text">线性表的顺序存储设计和实现（顺序表）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#顺序储存结构的设计原理"><span class="nav-number">2.1.</span> <span class="nav-text">顺序储存结构的设计原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#顺序储存结构的实现"><span class="nav-number">2.2.</span> <span class="nav-text">顺序储存结构的实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#声明接口类"><span class="nav-number">2.2.1.</span> <span class="nav-text">声明接口类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#声明一个实现接口类方法的类SeqList。及实现接口类各种方法的代码。"><span class="nav-number">2.2.2.</span> <span class="nav-text">声明一个实现接口类方法的类SeqList。及实现接口类各种方法的代码。</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#声明main主函数类测试实现接口和接口实现类"><span class="nav-number">2.2.3.</span> <span class="nav-text">声明main主函数类测试实现接口和接口实现类</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考"><span class="nav-number">2.3.</span> <span class="nav-text">参考:</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">葛木小舍先生</span>

  
</div>


<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共111.1k字</span>
</div>

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/gmxs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/gmxs/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/gmxs/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/gmxs/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/gmxs/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/gmxs/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/gmxs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("", "");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
